package com.st.controller.headend;

import com.ramostear.captcha.HappyCaptcha;
import com.st.entity.Admin;
import com.st.entity.User;
import com.st.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Controller
@RequestMapping("login1")
public class Login1Controller {
    @Autowired
    private IUserService userService;
   @RequestMapping("login")
    public String login(){
        return "/headend/login";
    }
    @RequestMapping("login1")
    public ModelAndView login1(User user, HttpServletRequest req,String captcha){
        ModelAndView mv=new ModelAndView();
        boolean flag = HappyCaptcha.verification(req,captcha,true);
        if (!flag){
            mv.addObject("errorMsg", "验证码错误！");
            mv.setViewName("/headend/login");
            return mv;
        }
            //md5加密和加盐处理
        String md5Pass2= String.valueOf(DigestUtils.appendMd5DigestAsHex(user.getUserPass().getBytes(StandardCharsets.UTF_8), new StringBuilder("wzf")));
        String md5Pass = DigestUtils.md5DigestAsHex(md5Pass2.getBytes(StandardCharsets.UTF_8));


        user.setUserPass(md5Pass);
        List<User> list = userService.query(user);
        if (list.size() == 0) {
            mv.addObject("errorMsg", "用户名不存在！");
            mv.setViewName("/headend/login");
            return mv;
        } else {
            if (user.getUserPhone().equals(list.get(0).getUserPhone()) && user.getUserPass().equals(list.get(0).getUserPass())) {
                HttpSession session=req.getSession();
                session.setAttribute("userId",list.get(0).getId());
                session.setAttribute("userPhone",list.get(0).getUserPhone());
                //设置过期事件
                session.setMaxInactiveInterval(60*10);
                mv.setViewName("redirect:/user/main");
                return mv;
            } else {
                mv.addObject("errorMsg", "用户名或密码错误！");
                mv.setViewName("/headend/login");
                return mv;
            }
        }
    }
    //注册
    @RequestMapping("enroll")
    public String enroll(){
    return "/headend/enroll";
    }
}
